<script setup>
import { ref, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import ItemSelectDialog from '@/views/warehousingentry/warehousingEntry/items.vue'
import { addApi } from '@/api/warehousingentry/warehousingEntry'
import { batchAddApi } from '@/api/warehousingentry/warehousingEntryDetails'

const emit = defineEmits(['refresh'])
const ruleFormRef = ref(null)
const rules = ref({
  batchNumber: [
    { required: true, message: '请输入批次号', trigger: 'blur' }
  ],
  consignorId: [
    { required: true, message: '请输入货主ID', trigger: 'blur' }
  ],
  totalCount: [
    { required: true, message: '请输入商品数量', trigger: 'blur' }
  ],
  predictedArrivalTime: [
    { required: true, message: '请选择预测到达时间', trigger: 'blur' }
  ],
  warehouseId: [
    { required: true, message: '请输入仓库ID', trigger: 'blur' }
  ]
})
const showItemSelect = ref(false)
const dialogVisible = ref(false)
const dialogFormData = ref({
  id: null,
  consignorId: null,
  batchNumber: '',
  totalCount: 0,
  predictedArrivalTime: '',
  warehouseId: null,
  damageCount: 0,
  surpassCount: 0,
  status: 1,
  lackCount: 0,
  saasId: null,
  isDel: 1
})
const selectedItems = ref([])

// 添加商品到列表
const addItem = (item) => {
  if (!selectedItems.value.some(i => i.id === item.id)) {
    selectedItems.value.push(item)
  }
}

// 删除某个商品
const removeItem = (index) => {
  selectedItems.value.splice(index, 1)
}
const props = defineProps({
  warehouseList: {
    default: () => []
  }
})
const resetForm = () => {
  showItemSelect.value = false
  dialogVisible.value = false
  dialogFormData.value = {
    id: null,
    consignorId: null,
    batchNumber: '',
    totalCount: 0,
    predictedArrivalTime: '',
    warehouseId: null,
    damageCount: 0,
    surpassCount: 0,
    status: 1,
    lackCount: 0,
    saasId: null,
    isDel: 1
  }
  ruleFormRef.value?.resetFields()
  selectedItems.value = []
}

const confirm = async () => {
  if (!ruleFormRef.value) return
  // 验证表单
  await ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        let entryRes = null
        let detailsRes = null
        entryRes = await addApi(dialogFormData.value)
        if (entryRes.code) {
          // const warehousingEntryId = entryRes.data.id || dialogFormData.value.id
          const warehousingEntryId = entryRes.data.id
          // 保存商品明细信息
          const detailsData = selectedItems.value.map(item => ({
            skuId: item.id,
            count: 1, // 默认每个商品数量为1，可根据需要调整
            supplierId: item.supplierId || 0,
            price: item.price || 0,
            warehousingEntryId: warehousingEntryId,
            predictedArrivalTime: dialogFormData.value.predictedArrivalTime,
            status: 1,
            saasId: dialogFormData.value.saasId,
            isDel: 1
          }))

          if (detailsData.length > 0) {
            detailsRes = await batchAddApi(detailsData)

            if (detailsRes.code) {
              ElMessage.success('操作成功!')
              resetForm()
              emit('refresh')
            } else {
              ElMessage.error('商品明细保存失败！')
            }
          } else {
            ElMessage.success('操作成功!')
            resetForm()
            emit('refresh')
          }
        } else {
          ElMessage.error('入库单保存失败！')
        }
      } catch (error) {
        ElMessage.error('操作异常！')
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
const onItemConfirm = (items) => {
  items.forEach(item => {
    addItem(item)
  })
  showItemSelect.value = false
}

const onItemCancel = () => {
  showItemSelect.value = false
}

defineExpose({
  dialogFormData,
  dialogVisible
})
</script>

<template>
  <el-dialog v-model="dialogVisible" title="入库单信息" width="1000px">
    <el-form :model="dialogFormData" label-width="120px" ref="ruleFormRef" :rules="rules">
      <el-form-item label="货主ID" prop="consignorId">
        <el-input v-model="dialogFormData.consignorId" placeholder="请输入货主ID" />
      </el-form-item>
      <el-form-item label="批次号" prop="batchNumber">
        <el-input v-model="dialogFormData.batchNumber" placeholder="请输入批次号" />
      </el-form-item>
      <el-form-item label="预测到达时间" prop="predictedArrivalTime">
        <el-date-picker v-model="dialogFormData.predictedArrivalTime" type="datetime" placeholder="请选择预测到达时间"
          style="width: 100%" />
      </el-form-item>
      <el-form-item label="仓库" prop="warehouseId">
        <el-select v-model="dialogFormData.warehouseId" placeholder="请选择仓库">
          <el-option v-for="warehouse in warehouseList" :key="warehouse.id" :label="warehouse.name"
            :value="warehouse.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品信息" v-if="selectedItems.length > 0">
        <el-table :data="selectedItems" style="width: 100%" border>
          <el-table-column prop="title" label="商品名称" />
          <el-table-column prop="code" label="商品编码" />
          <el-table-column prop="commodityCode" label="规格编码" />
          <el-table-column prop="supplierName" label="供应商名称" />
          <el-table-column prop="brandName" label="品牌" />
          <el-table-column prop="price" label="商品价格" />
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button size="small" type="danger" @click="removeItem(selectedItems.indexOf(row))">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button @click="showItemSelect = true" type="primary" style="float: right">+</el-button>
      </el-form-item>
      <!-- 添加商品选择弹窗 -->
      <item-select-dialog v-if="showItemSelect" v-model="showItemSelect" @confirm="onItemConfirm"
        @cancel="onItemCancel" />
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetForm">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>